package com.interview.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class MyData{
    volatile int number = 0;
    Lock lock = new ReentrantLock();

    public void addNum(){
        this.number = 100;
    }
    public  void addNumber(){
        try
        {
            lock.lock();//加锁
            this.number ++;
        } finally {
            lock.unlock();//解锁
        }

    }
}
public class VolatileDemo {

    public static void main(String[] args) {
        MyData myData = new MyData();
        //20个线程，每个线程执行1000次addNumber 20000
        for (int i = 0; i < 20; i++) {
            new Thread( () ->{
                for (int j = 0; j < 1000; j++) {
                    myData.addNumber();
                }

            },"线程"+i).start();
        }
        while(Thread.activeCount() > 2){

        }

        System.out.println("计算结果:"+ myData.number);

    }

    private static void testVisible() {
        MyData data = new MyData();

        new Thread( () ->{
            System.out.println(Thread.currentThread().getName()+"开始执行....");
            try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }
            data.addNum();
            System.out.println(Thread.currentThread().getName()+"结束执行...."+data.number);
        },"线程A").start();

        while (data.number == 0){

        }
        System.out.println("程序执行结束....game over");
    }

}
